package com.wgl.gsc.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.wgl.gsc.dao.OssFileMapper;
import com.wgl.gsc.service.IOssService;

@Controller
@RequestMapping("/oss")
public class OssController {
	@Resource
	private IOssService ossService;

	@RequestMapping("/uploadFile")
	public String toIndex(HttpServletRequest request, Model model) {
		return "fileUploadTest";
	}

	@RequestMapping("/upload")
	public String upload(HttpServletRequest request, Model model) throws IllegalStateException, IOException {
		// 将当前上下文初始化给 CommonsMutipartResolver （多部分解析器）
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		// 检查form中是否有enctype="multipart/form-data"
		if (multipartResolver.isMultipart(request)) {
			// 将request变成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			// 获取multiRequest 中所有的文件名
			Iterator iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				// 一次遍历所有文件
				MultipartFile file = multiRequest.getFile(iter.next().toString());
				if (file != null) {
					String fileName = file.getOriginalFilename();
					InputStream inputStream = file.getInputStream();
					String re = ossService.uploadToOss(inputStream, fileName);
				}
			}
		}
		return "success";
	}
}
